import axios, { AxiosInstance } from 'axios';
import { ErrorCode, ErrorCodeMap } from '@/utils/errorCodeMap';
import { ElMessage } from 'element-plus';
import { getCookie } from '@/utils/utils';
import { t } from '@/i18n';

class HttpRequest {
    baseUrl: any;

    queue: any;

    constructor(baseUrl: any) {
        this.baseUrl = baseUrl;
        this.queue = {};
    }

    getConfig() {
        return {
            baseURL: this.baseUrl,
            headers: {},
        };
    }

    destroy(url: any) {
        delete this.queue[url];
    }

    interceptors(instance: AxiosInstance, url: string | number) {
        // 请求拦截
        instance.interceptors.request.use(
            (config) => {
                if (!['/admin/login'].includes(config.url as string)) {
                    const token = getCookie('SaaS_Token');
                    if (!token) {
                        window.location.href = '/#/login';
                    }
                    config.headers.Authorization = token;
                }
                this.queue[url] = true;
                return config;
            },
            (error) => Promise.reject(error),
        );
        // 响应拦截
        instance.interceptors.response.use(
            (res): any => {
                const { code } = res.data;
                if (code === 440002 || code === 440004) {
                    ElMessage.error(t('responseMsg.loginTip', [res.data.message]));
                    window.location.href = '/#/login';
                }
                // 错误响应统一此处处理
                if (code !== 200) {
                    if (Object.prototype.hasOwnProperty.call(ErrorCodeMap, code)) {
                        const reservedErrorCode = code as ErrorCode
                        ElMessage.error(ErrorCodeMap[reservedErrorCode].value);
                        return Promise.reject(res.data);
                    }
                    ElMessage.error(res.data.message || t("responseMsg.unknownError"));
                    return Promise.reject(res.data);
                }
                this.destroy(url);
                return res.data;
            },
            (error: { response: any }) => {
                if (error?.response?.status === 401) {
                    ElMessage.error(t('responseMsg.pleaseLogin'));
                    window.location.href = '/#/login';
                }
                this.destroy(url);
                return Promise.reject(error);
            },
        );
    }

    request(opt: any): Promise<any> {
        const instance = axios.create();
        opt = Object.assign(this.getConfig(), opt);
        this.interceptors(instance, opt.url);
        return instance(opt);
    }
}

export default HttpRequest;
